package com.dhcc.DRGsHosp.infra.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


/**
 * @title		: JasperReportDataSource.java 
 * @description	: 
 * @author		: chl
 * @date		: 2017年1月15日
 * @version     : 2017
 * @copyright   : DHCC 
 */
public class JasperReportDataSource {
	private static final ThreadLocal<Connection> connectionTL = new ThreadLocal<Connection>(); 
	public static Connection getConnection(){
		Connection conn = (Connection)connectionTL.get() ;
		if( null == conn){
			Context ctx = null ;
			try {
				ctx = new InitialContext();
				// 找到DataSource
		        DataSource ds = (DataSource)ctx.lookup("java:comp/env/drgs") ;
		        // dataSource 获取连接
		        conn = ds.getConnection() ;
		        connectionTL.set(conn);
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}  
		return conn;
	}
	
	public static void closeResource(){
//		关闭资源
		Connection conn = (Connection)connectionTL.get() ;
		if(conn != null){
			try {
				connectionTL.set(null);
				conn.close();
				conn = null ;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
